﻿using System;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BLL;

public partial class ViewbyProduct_ZTEElectronicsList_ZTEElectronicsListToExcel : System.Web.UI.Page
{
    private TestItem ti;

    public ViewbyProduct_ZTEElectronicsList_ZTEElectronicsListToExcel()
    {
        ti = new TestItem();
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.Button5.Attributes.Add("onclick", "PasteData()");
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string productSN = this.TextBox2.Text.Trim();
        if (productSN.Length < 10)
        {
            string str1 = "成品序列号过短，请检查！";
            ClientScript.RegisterStartupScript(ClientScript.GetType(), "", "<script>alert('" + str1 + "');</script>");
        }
        else if (productSN.Length > 50)
        {
            string str1 = "成品序列号过长，请检查！";
            Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "click", "<script>alert('" + str1 + "');</script>");
        }
        else if (ProductSNCompare(productSN))
        {
            string str1 = "成品序列号已在列表中！";
            Page.ClientScript.RegisterStartupScript(ClientScript.GetType(), "click", "<script>alert('" + str1 + "');</script>");
        }
        else
        {
            this.ListBox1.Items.Add(productSN);
            this.Label1.Text = this.ListBox1.Items.Count.ToString();
            this.TextBox2.Text = "";
            this.TextBox2.Focus();
        }
    }

    protected void Button5_Click(object sender, EventArgs e)
    {
        string str = this.myVal.Value;
        string[] strs = str.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string st in strs)
        {
            if (!ProductSNCompare(st))
                this.ListBox1.Items.Add(st.Trim());
        }
        this.Label1.Text = this.ListBox1.Items.Count.ToString();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        ListItemCollection lic = new ListItemCollection();
        foreach (ListItem item in this.ListBox1.Items)
        {
            if (item.Selected)
                lic.Add(item);
        }
        foreach (ListItem item in lic)
        {
            this.ListBox1.Items.Remove(item);
        }
        this.Label1.Text = this.ListBox1.Items.Count.ToString();
    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        this.ListBox1.Items.Clear();
        this.Label1.Text = this.ListBox1.Items.Count.ToString();
    }


    protected bool ProductSNCompare(string psn)
    {
        foreach (ListItem item in this.ListBox1.Items)
        {
            if (item.Text == psn)
            {
                return true;
            }
        }
        return false;
    }

    protected void BiuldDT(DataTable dt)
    {
        dt.Columns.Add("ProductSN");
        DataRow dr;
        foreach (ListItem item in this.ListBox1.Items)
        {
            dr = dt.NewRow();
            dr["ProductSN"] = item.Text;
            dt.Rows.Add(dr);
        }
    }

    protected void Button4_Click(object sender, EventArgs e)
    {
        if (this.ListBox1.Items.Count == 0)
        {
            string str1 = "请先添加成品序列号！";
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "click", "<script>alert('" + str1 + "');</script>");
        }
        else
        {
            DataTable dt = new DataTable();
            BiuldDT(dt);
            string pID = this.DropDownList1.SelectedValue;
            DataTable TestItemdt = ti.GetDTTemplate(pID, dt).Tables[0];
            if (TestItemdt.Rows.Count == 0)
                Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('没有数据，不需要导出哈');</script>");
                //ScriptManager.RegisterStartupScript(this.UpdatePanel1, this.GetType(), "message", "<script language='javascript' defer>alert('没有数据，不需要导出哈');</script>", false);
            else
            {
                //导出Excel  
                ExcelImport(TestItemdt, "ZTEReport_" + pID);
            }
            dt.Dispose();
        }
        //DataSet ds = ti.GetDTTemplate("S102311004", DateTime.Parse("2014-01-10 07:30:00"), DateTime.Parse("2014-01-10 16:30:00"));
        //CreateExcel(ds, "1", "ZTEReport");
    }

    public void CreateExcel(DataSet ds, string typeid, string FileName)
    {
        HttpResponse resp;
        resp = Page.Response;
        resp.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        resp.AppendHeader("Content-Disposition", "attachment;filename=" + FileName);
        string colHeaders = "", ls_item = "";
        int i = 0;
        // 
        DataTable dt = ds.Tables[0];
        DataRow[] myRow = dt.Select("");
        // typeid=="1"為EXCEL文檔；typeid=="2"XML文檔 
        if (typeid == "1")
        {
            // 
            for (i = 0; i < dt.Columns.Count; i++)
            {
                if (i == dt.Columns.Count - 1)
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\n";
                }
                else
                {
                    colHeaders += dt.Columns[i].Caption.ToString() + "\t";
                }
            }
            // 
            resp.Write(colHeaders);
            // 
            foreach (DataRow row in myRow)
            {
                // 
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    if (i == dt.Columns.Count - 1)
                    {
                        ls_item += row[i].ToString() + "\n";
                    }
                    else
                    {
                        ls_item += row[i].ToString() + "\t";
                    }
                }
                // 
                resp.Write(ls_item);
                ls_item = "";
            }
        }
        else
        {
            if (typeid == "2")
            {
                //从DataSet中直接导出XML数据并且写到HTTP输出流中 
                resp.Write(ds.GetXml());
            }
        }
        //写缓冲区中的数据到HTTP头文件中 
        resp.End();
    }

    protected void ExcelImport(DataTable dt, string ExportFileName)
    {
        StringWriter sw = GetStringWriter(dt);
        //当前编码  
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        //把输出的文件名进行编码  
        string fileName = HttpUtility.UrlEncode(ExportFileName, System.Text.Encoding.UTF8);
        //文件名  
        string str = "attachment;filename=" + fileName + ".xls";
        //把文件头输出，此文件头激活文件下载框  
        HttpContext.Current.Response.AppendHeader("Content-Disposition", str);//http报头文件  
        HttpContext.Current.Response.ContentType = "application/ms-excel";
        this.Page.EnableViewState = false;
        Response.Write(sw);
        Response.End();
    }

    private StringWriter GetStringWriter(DataTable dt)
    {
        //DataTable dt = DTFormate(dt1);
        StringWriter sw = new StringWriter();
        #region 行列转换之前
        //读列名  
        //foreach (DataColumn dc in dt.Columns)
        //    sw.Write(dc.ColumnName + "\t");
        //读列值  
        //重新的一行  
        //sw.Write(sw.NewLine);
        //if (dt != null)
        //{
        //    foreach (DataRow dr in dt.Rows)
        //    {
        //        for (int i = 0; i < dt.Columns.Count; i++)
        //        {
        //            sw.Write(dr[i].ToString() + "\t");
        //        }
        //        sw.Write(sw.NewLine);
        //    }
        //}
        #endregion
        if (dt != null)
        {
            foreach (DataColumn column in dt.Columns)
            {
                sw.Write(column.ColumnName + "\t");
                foreach (DataRow row in dt.Rows)
                {
                    sw.Write(row[column] + "\t");
                }
                sw.Write(sw.NewLine);
            }
        }
        sw.Close();
        return sw;
    }
    
    //DataTable转置
    protected DataTable DTFormate(DataTable dt)
    {
        DataTable dtNew = new DataTable();
        dtNew.Columns.Add("ColumnName", typeof(string));
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            dtNew.Columns.Add("Column" + (i + 1).ToString(), typeof(string));
        }
        foreach (DataColumn dc in dt.Columns)
        {
            DataRow drNew = dtNew.NewRow();
            drNew["ColumnName"] = dc.ColumnName;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                drNew[i + 1] = dt.Rows[i][dc].ToString();
            }
            dtNew.Rows.Add(drNew);
        }
        return dtNew;
    }
}
